// http/1.0：每次请求都需要建立一个新的 tcp 连接
// http/1.1：可以持久连接，但是必须先进先出（浏览器有并发限制，一般是 6 个，同时这个也防止了 ddos 攻击）

/** 五种在循环中使用 async/await 的方法 */

function someAPICall(param) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('Resolved' + param);
    }, param);
  });
}

async function someFunction(items) {
  items.forEach(async i => {
    const res = await someAPICall(i);
    console.log('--->', res);
  });
}

someFunction(['3000', '8000', '1000', '4000']);

/** for of */
async function someFunction2(items) {
  for (const i of items) {
    const res = await someAPICall(i);
    console.log('--->', res);
  }
}

someFunction2(['3000', '8000', '1000', '4000']);

/** reduce */
let result = [3000, 2000, 1000, 4000].reduce((accumulatorPromise, nextID) => {
  return accumulatorPromise.then(() => {
    return someAPICall(nextID);
  });
}, Promise.resolve());

result.then(e => {
  console.log('All Promises Resolved !', e);
});

/** */
function sleep(i) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, i);
  });
}

async function promiseAll(arr) {
  await Promise.all(
    arr.map(async i => {
      await sleep(i);
      console.log('--->', i);
    })
  );
}

promiseAll(['3000', '8000', '1000', '4000']);
